package come.iweb.user.service;

import come.iweb.user.dao.UserDao;
import come.iweb.user.dao.UserDaoImpl;
import come.iweb.user.model.User;
import come.iweb.util.PasswordUtil;

/**
 * 用户服务实现类，实现UserService接口
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public User login(String username, String password) {
        // 参数验证
        if (username == null || username.trim().isEmpty() ||
            password == null || password.trim().isEmpty()) {
            return null;
        }
        
        // 调用DAO层方法验证用户
        return userDao.queryByUsernamePassword(username, password);
    }

    @Override
    public boolean register(User user) {
        // 参数验证
        if (user == null || user.getUsername() == null || user.getUsername().trim().isEmpty() ||
            user.getPassword() == null || user.getPassword().trim().isEmpty() ||
            user.getEmail() == null || user.getEmail().trim().isEmpty()) {
            return false;
        }
        
        // 检查用户名是否已存在
        if (isUsernameExists(user.getUsername())) {
            return false;
        }
        
        // 设置默认角色
        if (user.getRole() == null || user.getRole().trim().isEmpty()) {
            user.setRole("user");
        }
        
        // 加密密码
        user.setPassword(PasswordUtil.encryptPassword(user.getPassword()));
        
        try {
            // 调用DAO层方法保存用户
            return userDao.addOne(user) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean isUsernameExists(String username) {
        if (username == null || username.trim().isEmpty()) {
            return false;
        }
        
        User user = userDao.queryByUsername(username);
        return user != null;
    }

    @Override
    public User getUserById(Long id) {
        if (id == null) {
            return null;
        }
        
        return userDao.queryById(id);
    }

    @Override
    public boolean updateUser(User user) {
        if (user == null || user.getId() == null) {
            return false;
        }
        
        // 如果要更新密码，需要验证旧密码
        if (user.getOldpassword() != null && !user.getOldpassword().trim().isEmpty()) {
            // 加密新密码
            user.setPassword(PasswordUtil.encryptPassword(user.getPassword()));
            int result = userDao.updateUser(user);
            return result > 0;
        }
        
        // 如果只更新邮箱，不需要验证旧密码
        String sql = "UPDATE user SET email = ?, updatetime = NOW() WHERE id = ?";
        return userDao.updateUser(user) > 0;
    }

    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            return false;
        }
        
        return userDao.deleteById(id) > 0;
    }
}
